package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.common.exception.RRException;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    //redis中的购物车前缀
    private final String CART_PREFIX = "gulimall:cart:";

    /**
     * 加入购物车
     *
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public Cart addToCart(Long skuId, Integer num) {
        //购物车操作项 -- redis
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            //购物车没有该商品则添加到购物车

            CartItem item = new CartItem();
            //1.远程查询当前要添加的商品信息 -- 异步
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                item.setCheck(true);
                item.setCount(num);
                item.setImage(data.getSkuDefaultImg());
                item.setTitle(data.getSkuTitle());
                item.setSkuId(skuId);
                item.setPrice(data.getPrice());
            }, executor);

            //2.远程查询商品的属性列表 -- 异步
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                item.setSkuAttr(values);
            }, executor);

            //3.商品信息添加到购物车
            //等待所有的异步任务执行完毕
            try {
                CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();
            } catch (Exception e) {
                throw new RRException(BizCodeEnum.CART_ADDTOCART_EXCEPTION);
            }
            String s = JSON.toJSONString(item);
            cartOps.put(skuId.toString(), s);
        } else {
            //购物车有此商品则修改数量
            CartItem item = JSON.parseObject(res, CartItem.class);
            item.setCount(item.getCount() + num);
            String s = JSON.toJSONString(item);
            cartOps.put(skuId.toString(), s);
        }

        return cart();
    }

    /**
     * 获取购物车列表
     *
     * @return
     */
    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
            //合并购物车
            String tempCartkey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartkey);
            if (tempCartItems != null) {
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                clearCart(tempCartkey);
            }

            //获取登录后的购物车项，包含合并过来的购物项
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            //未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 清空购物车
     *
     * @param cartKey
     * @return
     */
    @Override
    public Cart clearCart(String cartKey) {
        //合并购物车后，删除临时购物车
        redisTemplate.delete(cartKey);
        return cart();
    }

    /**
     * 改变选中状态
     *
     * @param skuId
     * @param check
     * @return
     */
    @Override
    public Cart checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), s);
        return cart();
    }

    /**
     * 修改数量
     *
     * @param skuId
     * @param count
     * @return
     */
    @Override
    public Cart countItem(Long skuId, Integer count) {
        if (count <= 0)
            throw new RRException(BizCodeEnum.COMMON_PARAM_EXCEPTION);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(count);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), s);
        return cart();
    }

    /**
     * 删除某个购物项
     *
     * @param skuId
     * @return
     */
    @Override
    public Cart deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
        return cart();
    }

    /**
     * 获取当前用户选中的购物项
     *
     * @return
     */
    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null)
            return null;

        String cartKey = CART_PREFIX + userInfoTo.getUserId();
        List<CartItem> cartItems = getCartItems(cartKey);

        //获取选中的购物项
        List<CartItem> collect = cartItems.stream()
                .map(item->{
                    BigDecimal price = productFeignService.getPrice(item.getSkuId());
                    //价格更新为最新价格，不能使用购物车里的价格
                    item.setPrice(price);
                    return item;
                })
                .filter(item -> item.getCheck()).collect(Collectors.toList());
        return collect;
    }

    /**
     * 获取单个购物项
     *
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());

        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        return cartItem;
    }

    /**
     * 获取要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //gulimall:cart:1
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            //gulimall:cart:xxx
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(cartKey);
        return cartOps;
    }

    /**
     * 获取购物项列表
     *
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map(item -> {
                String str = item.toString();
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 获取当前用户的购物车，不合并（也可能是临时用户）
     *
     * @return
     */
    public Cart cart() {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        List<CartItem> cartItems = getCartItems(cartKey);
        cart.setItems(cartItems);
        return cart;
    }
}
